// 全局变量
var today = new Date();
var todayTxt = today.format('yyyy-MM-dd');

var MY_THREEDAY = (function() {

	function loadItem(){
		//清除排序
		var  oTable = document.getElementById("dataTable");
		oTable.sortCol = -1;
		//重置全部排序图标
		$("after").css("opacity",0.3);
		$("before").css("opacity",0.3);

		var params = getParams();
		if(params) {
            var $tbody = $('#tbodyViolateInstitutionList');
            $tbody.empty();

            WeKnow.loading();

            $.ajax({
                type: "POST",
                url: "invs_threeDay.do/load",
                dataType: "json",
                data: params,
                async: true,//异步调用
                success: function (data) {

                    WeKnow.closeLoading();

                    if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

                    if (data.errcode == 0) {
                        var e = '';//初始化
                        // 数据列表
                        if ('violateCntList' in data && data.violateCntList.length == 0) {
                            e += '<tr class="danger">';
                            e += '<td colspan=5 class="text-left">暂无数据</td>';
                            e += '</tr>';
                        } else {
							$(data.datalist).each(function( idx,_a){
								e+='<tr';
								e+= ' data-illegal_id="' + _a.id + '"';
								e+= ' data-institution_id="' + _a.institutionId + '"';
								e+= ' data-institution_name="' + _a.institutionName + '"';
								if ( _a.appeal && _a.appeal.appealAtta ){ //申诉图片
									e+= ' data-appeal_atta="' + _a.appeal.appealAtta + '"';
								}
								e+= '>';
								// 名称
								e+='<td class="text-center">'+ _a.institutionShortName + '</td>';
								// 日期
								e+='<td class="text-center">'+ new Date(_a.checkDt).format('yyyy-MM-dd') + '</td>';
								// 状态
								e+='<td class="text-center">'+ (_a.checkSt==0?'正常':'<font style="color:red;">异常</font>') +  '</td>';
								// 状态说明
								e+='<td class="text-center">'+ ( _a.message==null?'-':_a.message) + '</td>';
								// 操作时间
								e+='<td class="text-center"> '+ new Date(_a.appeal.updateTm).format('yyyy-MM-dd hh:mm:ss') +'</td>';
								// // 违规人员
								// e+='<td class="text-center"> '+ _a.doctorName +'</td>';
								// // 查看处方
//	        					e+='<td class="text-center pointer show_img"><img style="width: 25px;" src="https://wenuan-static.oss-cn-shanghai.aliyuncs.com/icon/pc/invs/photo.png"></td>';
// 								e+='<td class="text-center"><button class="btn btn-default btn-sm" style="margin-left: 5px;" name="showLocation" loginPosition="'+_a.detail.loginPosition+'">查看位置</button></td>';
// 								if (_a.detail.msgId=="850001"){
// 									e+='<td class="text-center"><button class="btn btn-default btn-sm" style="margin-left: 5px;" name="showLocation" loginPosition="'+_a.detail.loginPosition+'">查看位置</button></td>';
// 								}else {
// 									e+='<td class="text-center">-</td>';
// 								}
								// 处理状态
//	        					e+='<td class="text-center follow-status"> '+ (_a.detail.followStatus==0?'未跟进':'已跟进') +'</td>';
								// 种类
//	        					e+='<td class="text-center">';
////	        						e+='<button class="btn btn-default btn-sm" name="download">下载</button>';
//	        						if ( _a.detail.followStatus==0 ){
//		        						e+='<button class="btn btn-default btn-sm" style="margin-left: 5px;" name="follow_up">跟进</button>';
//	        						}
//	        					e+='</td>';
								// 申诉状态
								if (_a.appeal){
									e+='<td class="text-center">'+ MY_APPEAL.getAppealStTxt(_a.appeal.appealSt) +'</td>';// 申述状态
									e+='<td class="text-center">'+ (_a.appeal.appeal==null?'-':_a.appeal.appeal) +'</td>';// 申述内容

									// // 申述图片
									// if ( _a.appeal && _a.appeal.appealAtta ){
									// 	e+='<td class="text-center"><button type="button" name="showAppealAtta" class="btn btn-default btn-sm">查看</button></td>';
									// } else {
									// 	e+='<td class="text-center">-</td>';
									// }

									e+='<td class="text-center">'+ (_a.appeal.feedback==null?'-':_a.appeal.feedback) +'</td>';//处理意见
									e+='<td class="text-center">'+ (_a.appeal.supervisorName==null?'-':_a.appeal.supervisorName) +'</td>';	// 处理人
									// 操作按钮区  根据申诉表的信息控制显示的按钮
									if (_a.checkSt == 0) {
										e+='<td class="text-center">-</td>';
									} else {
										if ( _a.appeal.appealSt == 1){
											e+='<td class="text-center"><button type="button" name="check" class="btn btn-default btn-sm">申诉处理</button></td>';
										} else if ( _a.appeal.appealSt == 0 ) {
											e+='<td class="text-center"><button type="button" name="closeIllegal" class="btn btn-default btn-sm">取消异常</button></td>';
										}
									}
								}else{
									// e+='<td class="text-center">-</td>';
									e+='<td class="text-center">-</td>';
									e+='<td class="text-center">-</td>';
									e+='<td class="text-center">-</td>';
									e+='<td class="text-center">-</td>';
									e+='<td class="text-center">-</td>';
								}
								e+='</tr>';
							});
						}
						$tbody.append(e);

                    } else if (data.errcode == -1) {
                        WeKnow.errorMsg(data.errMsg);
                    } else {
                        WeKnow.systemMsg('查询失败，请重新登录后再试');
                    }
                }
            });
        }
	}


	// 收集页面查询参数
	function getParams(){

		var data = {};

		// 标本日期 from - to
		var $dtFrom = $('#dtFrom');
        var $dtTo = $('#dtTo');

		if ( !$dtFrom.val().length ){
			WeKnow.errorMsg('请输入查询开始日期');
			$dtFrom.focus();
			return false;
		}

		data.businessType=70;

		var dtFrom = $dtFrom.val();
		if ( !MY_VALIDATOR.isDate(dtFrom,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询开始日期格式不正确');
			$dtFrom.focus();
			return false;
		}
		data.dtFrom = dtFrom;

		// 查询日期to

		if ( !$dtTo.val().length ){
			WeKnow.errorMsg('请输入查询结束日期');
			$dtTo.focus();
			return false;
		}

		var dtTo = $dtTo.val();
		if ( !MY_VALIDATOR.isDate(dtTo,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询结束日期格式不正确');
			$dtTo.focus();
			return false;
		}
        if($dtFrom.val()>$dtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
		data.dtTo = dtTo;

		// 登记状态
		var registryStatus =  $('#registryStatus').val();
		data.registryStatus = registryStatus;
		// 诊所名
		var institutionName = $.trim( $('input[name="institutionName"]').val());
		if ( institutionName.length ){
			data.institutionName = institutionName;
		}

		// 地区ID
		var townId =  $('#townId').val();
		if ( townId.length ){
			data.townId = townId;
		}

		return data;
	}

	// 收集页面查询参数
	function getDetailParams(){

		var data = {};

		// 标本日期 from - to
		var $dtFrom = $('#dtFrom');
		if ( !$dtFrom.val().length ){
			WeKnow.errorMsg('请输入查询开始日期');
			$dtFrom.focus();
			return false;
		}

		var dtFrom = $dtFrom.val();
		if ( !MY_VALIDATOR.isDate(dtFrom,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询开始日期格式不正确');
			$dtFrom.focus();
			return false;
		}
		data.dtFrom = dtFrom;
		data.businessType=70;
		// 查询日期to
		var $dtTo = $('#dtTo');
		if ( !$dtTo.val().length ){
			WeKnow.errorMsg('请输入查询结束日期');
			$dtTo.focus();
			return false;
		}

		var dtTo = $dtTo.val();
		if ( !MY_VALIDATOR.isDate(dtTo,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询结束日期格式不正确');
			$dtTo.focus();
			return false;
		}
        if($dtFrom.val()>$dtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
		data.dtTo = dtTo;
		// // 处方违规类别
		// if ($('#msgId').val()!=9){
		// 	data.msgId = $('#msgId').val();
		// }
		// 状态
		if ($('#threeDay_checkst').val()!=9){
			data.checkSt = $('#checkSt').val();
		}

		data.institutionId = $('#institutionId').val();

		return data;
	}


	return {
		getParams:getParams,
		getDetailParams:getDetailParams,
		loadItem:loadItem
	}
})();

$(document).ready(function() {

	// 页面初期数据查询
	MY_THREEDAY.loadItem();

	$(".my_date_control" ).datepicker({
		changeMonth: true,
		changeYear: true,
        dateFormat: 'yy-mm-dd',//日期格式
        yearSuffix: '年', //年的后缀
        showMonthAfterYear:true,//是否把月放在年的后面
        maxDate: (function() {
        	return todayTxt;
        })(),//最大日期
        yearRange: (function() {
        	// '1990:2010'
        	var year1 = '1900';
        	var year2 = today.getFullYear();
        	return year1 + ':' + year2;
        })(),
        monthNamesShort: ['01','02','03','04','05','06','07','08','09','10','11','12'],
        dayNamesMin: ['日','一','二','三','四','五','六'],
        onUpdatedDatepicker: function(_year, _month, _calendar) {
        	console.log('onUpdatedDatepicker');
        	var $c = $('div#ui-datepicker-div');
			$c.find('td[data-handler="selectDay"]').each(function(idx, d) {
				var $d = $(d);
				$d.css({'pointer-events': 'auto', 'opacity': 1});
    		});
        }
	});

	$('#registryStatus').on('change',function(){
		MY_THREEDAY.loadItem();
	});
	$('#search').on('click',function(){
		MY_THREEDAY.loadItem();
	});


	var $thead= $('thead#thead-remote');
	var $tbody= $('tbody#tbody-remote');// 明细


	// $('#tbody-remote').on('click','button[name="showDetail"]',function(){
	// 	var $that = $(this);
	// 	var $parentTr = $that.closest('tr');
	// 	var institutionId = $parentTr.data('institution_id');
	// 	$('#institutionId').val(institutionId);
	// 	// 机构名
	// 	var institutionName = $parentTr.data('institution_name');
	// 	// $('#institutionName').val(institutionName);
	//
	// 	var params = MY_REMOTE.getDetailParams();
    //    if(params) {
    // MY_REMOTE_COM.loadDetailItem(params, $thead, $tbody);
    // // 子页面显示诊所名
    // $('#institution_name_dis').text(institutionName + '(' + $('#dtFrom').val() + '-' + $('#dtTo').val() + ')');
	//
    // $('.input-toggle').toggle();}
	// });
	//
	// $('#backToWorkspace').on('click',function(){
	// 	$('.input-toggle').toggle();
	// });
	// // 下拉框变化时刷新
	// $('#msgId,#checkSt').on('change',function(){
	// 	var params = MY_REMOTE.getDetailParams();
    //     if(params) {
    //         MY_REMOTE_COM.loadDetailItem(params, $thead, $tbody);
    //     }
	// });

	// // 跟进
	// $tbody.on('click','button[name="follow_up"]',function(){
	//
	// 	var $that = $(this);
	// 	var $parentTr = $that.closest('tr');
	//
	// 	WeKnow.loading();
	//
	// 	$.ajax({
	//         type: "POST",
	//         url: "invs_prescription_violate.do/update",
	//         data: {violateId:$parentTr.data('violate_id'),institutionId:$parentTr.data('institution_id')},
	//         async: true,//异步调用
	//         success: function(data) {
	//
	//         	WeKnow.closeLoading();
	//
	// 			if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	//
	//         	if (data.errcode == 0) {
	//         		$parentTr.find('.follow-status').text('已跟进');
	//         		$parentTr.find('button[name="follow_up"]').remove();//删除跟进按钮
	//         		WeKnow.successMsg('更新成功');
	//         	} else if (data.errcode == -1 ) {
	//         		WeKnow.errorMsg( data.errMsg );
	//         	} else {
	//         		WeKnow.systemMsg('更新失败，请重新登录后再试');
	//         	}
	//         }
	// 	});
	// });
	//
	// // 查看处方
	// $tbody.on('click','button[name="showPre"]',function(){
	//
	// 	var $that = $(this);
	// 	var $parentTr = $that.closest('tr');
	//
	// 	WeKnow.loading();
	//
	// 	$.ajax({
	//         type: "POST",
	//         url: "invs_prescription_violate.do/show_prescription",
	//         data: {violateId:$parentTr.data('violate_id'),institutionId:$parentTr.data('institution_id')},
	//         async: true,//异步调用
	//         success: function(data) {
	//
	//         	WeKnow.closeLoading();
	//
	// 			if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	//
	//         	if (data.errcode == 0) {
	//         		MY_WEST_PRESCRIPTION.resetPrintBody(data.outpatient);
	//         		var keepAttr = ["class", "style"];
	//     			var options = {retainAttr: keepAttr};
	//     			$('#printDiv').printArea(options);
	//         	} else if (data.errcode == -1 ) {
	//         		WeKnow.errorMsg( data.errMsg );
	//         	} else {
	//         		WeKnow.systemMsg('查看处方失败，请重新登录后再试');
	//         	}
	//         }
	// 	});
	// });
	//
	// // 显示申诉图片
	// $('#tbody-prescription').on('click','button[name="showAppealAtta"]',function(){
	// 	var $that = $(this);
	// 	var $parentTr = $that.closest('tr');
	//
	// 	var appealAtta = $parentTr.data('appeal_atta');
	// 	var institutionId = $('#institutionId').val();
	// 	// 显示交接单图片
	// 	MY_SHOW_IMG.createShowImgModal(institutionId ,appealAtta);
	// });

	// 处理申诉 OR 取消异常   注：申诉处理由于多个页面共用，故提炼成appeal.js
	$('#tbody-threeDay').on('click','button[name="closeIllegal"],button[name="check"]',function(){
		var $that = $(this);
		var $parentTr = $that.closest('tr');

		var illegalId = $parentTr.data('illegal_id');
		var originBtnName= $that.prop('name');
		// 更新用模态框
		// 更新用模态框
		var $tHead  = $('#thead-threeDay');
		var $tbody = $('#tbody-threeDay');
		var params = MY_SM_threeDay.getParams();
        if(params) {
            MY_APPEAL.createModalWin
            (illegalId, originBtnName,
                function () {
					MY_SUMMARIZE.getSummarize();//刷新各TAB的总件数
                    MY_THREEDAY_COM.loadDetailItem(params, $thead, $tbody);
                }
            );
        }
	});

	// // 导出
	// $('a#export').on('click',function(){
	//
	// 	var $that = $(this);
	//
	// 	var data = {};
	// 	data.startDt = new Date().format("yyyy-MM-dd");
	// 	data.endDt = data.startDt;
	//
    // 	var url = WeKnow.getRealPath() + '/invs_prescription_violate.do/output';
	//
    // 	WeKnow.loading();
    // 	$.fileDownload(url,
    // 		{
    //         httpMethod: 'POST',
    //         data: data,
    //         prepareCallback:function(url){
    //         	console.log('download start')
    //         	WeKnow.loading();
    //         },
    //         successCallback:function(url){
    //         	console.log('download end')
    //         	WeKnow.closeLoading();
    //         },
    //         failCallback: function (html, url) {
    //         	WeKnow.errorMsg('下载失败');
    //         }
    //      });
	// });


});